package com.itheima.health.controller;

import com.alibaba.druid.util.StringUtils;
import com.itheima.health.common.MessageConst;
import com.itheima.health.common.RedisConst;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.SetMealService;
import com.itheima.health.utils.QiniuUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("setmeal")
public class SetMealController {
    @Autowired
    private SetMealService setmealservice;

    @Autowired
    private QiniuUtils qiniuUtils;

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 套餐查询
     * @return
     */
    @GetMapping("/findPage")
    public Result  findPage( QueryPageBean queryPageBean) {
        log.info("套餐查询:{}",queryPageBean);
        PageResult pageResult = setmealservice.findPage(queryPageBean);
        return new Result(true, MessageConst.ACTION_SUCCESS,pageResult);
    }

    /**
     * 图片上传
     */
    @PostMapping("/upload")
    public Result upload(@RequestParam("imgFile") MultipartFile imgFile){
        log.info("图片上传:{}",imgFile.getOriginalFilename());
        //获取原始名字
        String originalFilename = imgFile.getOriginalFilename();

        String fileName = System.currentTimeMillis()+"_"+UUID.randomUUID().toString().replace("-", "") + "_" + originalFilename;

        //将图片的名字添加到redis中
        redisTemplate.boundSetOps(RedisConst.SETMEAL_IMG_NAME).add(fileName);
        // 上传文件到服务器
        try {
            InputStream  in = imgFile.getInputStream();
            qiniuUtils.upload2Qiniu(in, fileName);

        } catch (IOException e) {
            return new Result(false, MessageConst.PIC_UPLOAD_FAIL);
        }
        String imgName =   qiniuUtils.getUrlPrefix() + fileName;
        return new Result(true, MessageConst.ACTION_SUCCESS, imgName);
    }


    /**
     * 新增套餐
     */
    @PostMapping("/add")
    public Result add(@RequestBody Setmeal setmeal,Integer[] checkgroupIds){
        log.info("新增套餐：{}",setmeal);
        if(!StringUtils.isEmpty(setmeal.getImg())) {
            String img =setmeal.getImg().replace(qiniuUtils.getUrlPrefix(),"");
            setmeal.setImg(img);
        }
        setmealservice.save(setmeal,checkgroupIds);

        //// 从redis中清除记录的图片
       redisTemplate.boundSetOps(RedisConst.SETMEAL_IMG_NAME).remove(setmeal.getImg());

        return new Result(true, MessageConst.ACTION_SUCCESS,null);
    }
}
